package com.devin.service.config;

import com.devin.pojo.Permission;
import com.devin.pojo.Role;
import com.devin.service.PermissionService;
import com.devin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component("myFilterInvocationSecurityMetadataSource")
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private PermissionService permissionService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        System.out.println("requestUrl:"+requestUrl);
        List<Permission> permissions = permissionService.getPermissionsAndRoles();
        ArrayList<String> roles = new ArrayList<>();
        for (Permission permission : permissions) {
            String url = permission.getUrl();
            System.out.println("permissionURL:"+url);
            if (requestUrl.equals(url)) {
                List<Role> roles1 = permission.getRoles();
                for (Role each : roles1) {
                    String roleName = each.getRoleName();
                    roles.add("ROLE_"+roleName);
                    System.out.println("roleName:"+roleName);
                }
            }
        }
        String[] strings = new String[roles.size()];

        //到java方法中给对应url添加权限
        return SecurityConfig.createList(roles.toArray(strings));
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return ConfigAttribute.class.isAssignableFrom(aClass);
    }
}
